/////////////////////////////////////////////////////////////
// TITLE: 			Panelify HD Splits
//
// DESCRIPTION:
// Reform the data from a single annual file (as in the HD files) to a panel of all bond/equity security holdings.
// Classify each panel item at the MasterPortfolioId:Security level
// Generate new rows so that funds always report maturities/selling out of a security
// Generate flow size in USD per security holding, and a constant fx marketvaluation
/////////////////////////////////////////////////////////////

local part = `1'
local vars_to_keep = "MasterPortfolioId DomicileCountryId iso_currency_code date_m mns_class mns_subclass cusip currency_id numberofshare sharechange marketvalue maturitydate lcu_per_usd_eop"

use `vars_to_keep' using "$reconstruct/HD_part_`part'"
order `vars_to_keep'

// Initial clean
keep if mns_class == "B" | mns_class == "E"
gen security_ident = cusip
drop if missing(security_ident)
drop if missing(currency_id)
gen marketvalueusd = marketvalue / lcu_per_usd_eop

// Collapse at the MasterPortfolioId:Date:Security level as some fund split positions up
collapse (sum) marketvalueusd numberofshare sharechange (firstnm) DomicileCountryId iso_currency_code mns_class mns_subclass iso_country_code currency_id maturitydate, by(MasterPortfolioId date_m security_ident)
egen id=group(MasterPortfolioId security_ident)

// Make panel
tsset id date_m
tsfill, full

// Within each id (i.e. MPID:security_ident) replace the Domicile/iso_country/mns_class/mns_subclass/currency_id), replace the missing with the nonmissing details
foreach var of varlist MasterPortfolioId iso_currency_code security_ident DomicileCountryId mns_class mns_subclass iso_country_code currency_id maturitydate {
	capture confirm numeric variable `var'
	if !_rc {
		bysort id (`var') : replace `var' = `var'[1]
	}
	else {
		bysort id (`var') : replace `var' = `var'[_N]
	}
}
save "$reconstruct/intermediate/HD_part_`part'_panel_intermediate", replace emptyok
